import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { LoginService } from 'src/app/login/login.service';
import { StudentsGetDto } from './dto/students.get.dto';
import { GetStudentsQueryDto } from './dto/get-students-query.dto';
import { CreateStudentDto } from './dto/create-student.dto';
import { UpdateStudentDto } from './dto/update-student.dto';
import { StudentsPatchDto } from './dto/students.patch.dto';
import { StudentsPostDto } from './dto/students.post.dto';
import { StudentsDeleteDto } from './dto/students.delete.dto';
import { SendMessageDto } from './dto/send-message.dto';
import { MessagePostDto } from './dto/message.post.dto';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json'
  })
};

@Injectable({
  providedIn: 'root'
})
export class StudentsService {
  constructor(private http: HttpClient, private loginService: LoginService) {
    httpOptions.headers = httpOptions.headers.set(
      'Authorization',
      `Bearer ${this.loginService.getToken()}`
    );
  }

  getStudents({ className }: GetStudentsQueryDto) {
    const options = {
      ...httpOptions,
      params: className ? new HttpParams().set('className', className) : {}
    };

    return this.http.get<StudentsGetDto[]>('/api/students', options);
  }

  createStudent(createStudentDto: CreateStudentDto) {
    return this.http.post<StudentsPostDto>(
      '/api/students',
      createStudentDto,
      httpOptions
    );
  }

  // tslint:disable-next-line: variable-name
  deleteStudent(_id: string) {
    const options = {
      ...httpOptions,
      body: _id ? { students: [_id] } : {}
    };

    return this.http.delete<StudentsDeleteDto>('/api/students', options);
  }

  // tslint:disable-next-line: variable-name
  updateStudent(_id: string, updateStudentDto: UpdateStudentDto) {
    return this.http.patch<StudentsPatchDto>(
      '/api/students/' + _id,
      updateStudentDto,
      httpOptions
    );
  }

  sendMessage(sendMessageDto: SendMessageDto) {
    this.http
      .post(
        '/api/mail',
        {
          to: sendMessageDto.to.join(', '),
          subject: sendMessageDto.subject,
          text: sendMessageDto.text
        },
        httpOptions
      )
      .subscribe();
    return this.http.post<MessagePostDto>(
      '/api/message',
      sendMessageDto,
      httpOptions
    );
  }
}
